<template>
  <div>
    <textarea :id="id"></textarea>
  </div>
</template>

<script>
  import 'simplemde/dist/simplemde.min.css'
  import SimpleMde from 'simplemde'
  export default {
    name: 'makedownEditor',
    props:{
      //支持v-model指令：组件需要实现value属性和input事件
      value: String,
      id: {
        type: String,
        default: "markdown-"+ +new Date()
      },
    },
    data: function () {
      return {
        propValueChanged: false
      }
    },
    watch: {
      value: function (newValue) {
        if(newValue === this.mde.value()) return

        this.propValueChanged = true
        this.mde.value(newValue)
      }
    },
    mounted: function () {
      this.mde = new SimpleMde({
        element: document.getElementById(this.id),
        autoDownloadFontAwesome: true,

      })

      this.propValueChanged = false
      if(this.value){
        this.mde.value(this.value)
      }

      //定义mde内容发生变化时的change事件处理程序
      let self = this
      this.mde.codemirror.on("change", function () {
        if(self.propValueChanged){
          self.propValueChanged = false
          return;
        }

        //发出input事件，
        self.$emit('input', self.mde.value())
      })
    },
    destroyed: function () {
      this.mde = null
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>

</style>
